package cn.sgjk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.sgjk.train.business.domain.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.sgjk.train.common.resp.PageResp;
import cn.sgjk.train.common.util.SnowUtil;
import cn.sgjk.train.business.mapper.DailyTrainSeatMapper;
import cn.sgjk.train.business.req.DailyTrainSeatQueryReq;
import cn.sgjk.train.business.req.DailyTrainSeatSaveReq;
import cn.sgjk.train.business.resp.DailyTrainSeatQueryResp;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
public class DailyTrainSeatService {

    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainSeatService.class);

    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;

    @Autowired
    private TrainSeatService trainSeatService;

    public void save(DailyTrainSeatSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(req, DailyTrainSeat.class);
        if (ObjectUtil.isNull(dailyTrainSeat.getId())) {
            dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainSeat.setCreateTime(now);
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.insert(dailyTrainSeat);
        } else {
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.updateByPrimaryKey(dailyTrainSeat);
        }
    }

    public PageResp<DailyTrainSeatQueryResp> queryList(DailyTrainSeatQueryReq req) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.setOrderByClause("id asc");
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria();

        if(ObjectUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainSeat> dailyTrainSeatList = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);

        PageInfo<DailyTrainSeat> pageInfo = new PageInfo<>(dailyTrainSeatList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainSeatQueryResp> list = BeanUtil.copyToList(dailyTrainSeatList, DailyTrainSeatQueryResp.class);

        PageResp<DailyTrainSeatQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        dailyTrainSeatMapper.deleteByPrimaryKey(id);
    }

    public void genSeat(Date date, String trainCode) {
        LOG.info("生成日期{}的车厢车座:{} 信息开始", DateUtil.formatDate(date),trainCode);

        //删除已有当天数据
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date).andTrainCodeEqualTo(trainCode);
        dailyTrainSeatMapper.deleteByExample(dailyTrainSeatExample);

        // 查出某车次全部车厢信息
        List<TrainSeat> trainSeats = trainSeatService.selectAll(trainCode);
        if (CollUtil.isEmpty(trainSeats)) {
            LOG.info("该车厢没有车座基础数据，生成该车厢的车座信息结束");
            return;
        }

        int trainSeatSum = trainSeats.size();
        CountDownLatch downLatch = new CountDownLatch(trainSeatSum);

        for (TrainSeat trainSeat: trainSeats) {
            LOG.info("开始生成{}车次的车座",trainSeat.getTrainCode());
            new Thread(()->{
                long start = System.currentTimeMillis();

                DateTime now = new DateTime();
                DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(trainSeat, DailyTrainSeat.class);
                dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainSeat.setSell("000");
                dailyTrainSeat.setDate(date);
                dailyTrainSeat.setCreateTime(now);
                dailyTrainSeat.setUpdateTime(now);
                dailyTrainSeatMapper.insert(dailyTrainSeat);

                long end = System.currentTimeMillis();
                downLatch.countDown();
                LOG.info("生成{}车次的车座完成,用时{}",trainSeat.getTrainCode(),(end - start));
            }).start();

        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            LOG.error("每日车次生成失败",e);
        }
        LOG.info("生成日期{}的车厢车座:{} 信息结束", DateUtil.formatDate(date),trainCode);
    }

    public int countSeat(Date date, String code) {
        return countSeat(date,code,null);
    }

    public int countSeat(Date date, String code, String typeSeat) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria().andDateEqualTo(date)
                .andTrainCodeEqualTo(code);

        if(StrUtil.isNotBlank(typeSeat)) {
            criteria.andSeatTypeEqualTo(typeSeat);
        }

        int count = (int) dailyTrainSeatMapper.countByExample(dailyTrainSeatExample);
        if(count == 0)
        {
            return -1;
        }
        LOG.info("{}等座一共有{}张票",typeSeat,count);
        return count;
    }

    public List<DailyTrainSeat> selectByCarriage(Date date, String trainCode, Integer carriage, String seatType) {
        DailyTrainSeatExample example = new DailyTrainSeatExample();
        example.setOrderByClause("carriage_seat_index asc");
        example.createCriteria().andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andCarriageIndexEqualTo(carriage)
                .andSeatTypeEqualTo(seatType);
        return dailyTrainSeatMapper.selectByExample(example);
    }
}
